package com.lyrcsoft.springmvc.init.handler.mapping;

import com.lyrcsoft.springmvc.annotation.RequestMapping;
import com.lyrcsoft.springmvc.servlet.RequestMappingInfo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * {@link InstantiationAwareBeanPostProcessor}
 *
 * @author fujc-dev@qq.com
 * @version 1.0
 */
@Component
public class AnnotationHandlerMapping implements HandlerMapping, InstantiationAwareBeanPostProcessor {
    private static final Map<String, RequestMappingInfo> map = new HashMap<>();


    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        Method[] methods = bean.getClass().getMethods();
        for (Method method : methods) {
            RequestMappingInfo requestMappingInfo = createRequestMappingInfo(method, bean);
            map.put(requestMappingInfo.getUri(), requestMappingInfo);
        }
        return true;
    }

    @Override
    public Object getHandlerMapping(String requestUri) {
        return map.get(requestUri);
    }

    private RequestMappingInfo createRequestMappingInfo(Method method, Object bean) {
        RequestMappingInfo mappingInfo = new RequestMappingInfo();
        if (method.isAnnotationPresent(RequestMapping.class)) {
            mappingInfo.setMethod(method);
            mappingInfo.setUri(method.getDeclaredAnnotation(RequestMapping.class).value());
            mappingInfo.setObj(bean);
        }
        return mappingInfo;
    }
}
